


import 'package:baby/Entities/DataContext.dart';
import 'package:baby/Entities/Store/CartItem.dart';
import 'package:baby/StateManagement/ModelProvider.dart';
import 'package:baby/StateManagement/ObservableList.dart';
import 'package:baby/UI/Widgets/CustomSlider.dart';
import 'package:baby/UI/Widgets/NumberInput.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

class CartPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _CartPageState();
  }
}

class _CartPageState extends State<CartPage> {
  ScrollController _controller = ScrollController();
  SlidableController _slidableController = SlidableController();

  T _reduce<T>(Iterable<T> list, T defaultValue, T combine(T previous, T current)) {
    if (list.isEmpty) list = <T>[defaultValue];
    return list.reduce(combine);
  }

  @override
  Widget build(BuildContext context) {
    var dataContext = ModelContainer.of<DataContext>(context).model;

    return ModelDescendant<MyObservableList<CartItem>>(
      referenceModel: dataContext.cart,
      onChanged: (context, _, products) {

        Widget widget = Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            title: Text("مال ھارۋام"),
            elevation: 0.0,
          ),
          body: Column(
            children: <Widget>[
              AnimatedBuilder(
                animation: _controller,
                builder: (context, child){
                  var offset = 0.0;
                  if (_controller.positions.isNotEmpty) {
                    offset = _controller.offset;
                  }

                  var height = offset < 150 ? 150 - offset : 0.0;
                  var scale = height / 150 / 1;

                  Widget buildingWidget = Container(
                      height: height > 150 ? height : 150,
                      child: Stack(
                        children: <Widget>[
                          Column(
                            children: <Widget>[
                              Expanded(flex: 1, child: Container(
                                color: Theme.of(context).primaryColor,
                              ),),
                              Expanded(flex: 1, child: SizedBox(),),
                            ],
                          ),
                          Positioned(
                              top: 20.0,
                              left: 20.0,
                              right: 20.0,
                              bottom: 20.0,
                              child: Transform(
                                transform: Matrix4.translationValues(0.0, -offset, 0.0)..scale(scale, scale)..rotateZ(1 - scale),
                                child: child,
                                alignment: Alignment.center,
                              )
                          )
                        ],
                      ),
                  );

                  buildingWidget = SizedOverflowBox(
                    size: Size(double.infinity, height),
                    child: buildingWidget,
                  );

                  return buildingWidget;
                },
                child: Card(
                    elevation: 5.0,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20.0)
                    ),
                    child: Padding(
                      padding: EdgeInsets.symmetric(vertical: 10.0),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Expanded(
                              child: Center(
                                child: Text("${_reduce<double>(products.map((p) => p.count * p.product.price), 0.0, (previous, current) => previous + current).toStringAsPrecision(4)}฿", style: TextStyle(fontSize: 26.0),),
                              )
                          ),
                          Text("جەمئىي ${products.length} خىل، ${_reduce<double>(products.map((p) => p.count), 0.0, (previous, current) => previous + current)} دانە تاۋار"),
                        ],
                      ),
                    )
                ),
              ),
              Expanded(
                child: products.isEmpty ? Center(child: Text("No items"),) : ListView(
                  controller: _controller,
                  children: products.map((cartItem) => _buildCartItem(dataContext, cartItem)).toList(),
                ),
              ),
            ],
          )
        );

        widget = Directionality(
          child: widget,
          textDirection: TextDirection.rtl,
        );
        return widget;
      },
    );
  }

  Widget _buildCartItem(DataContext dataContext, CartItem cartItem){
    Widget childWidget = InkWell(
      child: ModelDescendant<CartItem>(
        referenceModel: cartItem,
        onChanged: (context, _, model) => Container(
          height: 100.0,
          decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.02),
              borderRadius: BorderRadius.circular(15.0)
          ),
          margin: EdgeInsets.all(15.0).copyWith(top: 0.0,),
          padding: EdgeInsets.symmetric(vertical: 15.0),
          child: Row(
            children: <Widget>[
              SizedBox(width: 15.0,),
              AspectRatio(
                aspectRatio: 1.0,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(15.0),
                  child: CachedNetworkImage(imageUrl: model.product.coverImage, fit: BoxFit.cover,),
                )
              ),
              SizedBox(width: 15.0,),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(model.product.name.ug, style: TextStyle(fontSize: 18.0),),
                    Row(
                      textBaseline: TextBaseline.alphabetic,
                      crossAxisAlignment: CrossAxisAlignment.baseline,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Text("฿"),
                        Text("${(model.product.price * model.count).toStringAsPrecision(3)}", textDirection: TextDirection.ltr, style: TextStyle(fontSize: 30.0, color: Colors.black.withOpacity(0.6)),),
                        Text("${model.count.toStringAsPrecision(3)} x ${model.product.price.toStringAsPrecision(3)} = ", textDirection: TextDirection.ltr, style: TextStyle(fontSize: 16.0),),
                      ],
                    ),
                  ],
                ),
              ),
              IconButton(
                icon: Icon(Icons.more_vert),
                onPressed: (){

                },
              )
            ],
          ),
        ),
      )
    );

    childWidget = Slidable(
      key: ObjectKey(cartItem.product.guid),
      child: childWidget,
      controller: _slidableController,
      actionPane: SlidableDrawerActionPane(),
      actions: <Widget>[
        Transform.translate(
          offset: Offset(0.0, -8.0),
          child: Row(
            children: <Widget>[
              Container(
                height: 90.0,
                width: 45.0,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15.0),
                  color: Colors.black.withOpacity(0.05),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    InkWell(
                      child: Padding(padding: EdgeInsets.all(10.0), child: Icon(Icons.add),),
                      onTap: (){},
                    ),
                    InkWell(
                      child: Padding(padding: EdgeInsets.all(10.0), child: Icon(Icons.remove),),
                      onTap: (){},
                    ),
                  ],
                ),
              ),
              Container(
                  margin: EdgeInsets.symmetric(horizontal: 5.0),
                  height: 90.0,
                  width: 45.0,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(15.0),
                    color: Colors.black.withOpacity(0.05),
                  ),
                  child: InkWell(
                    child: Icon(Icons.delete_forever),
                    onTap: (){},
                  )
              ),
            ],
          ),
        )
      ],
    );

    return childWidget;
  }
}
